//
//  ReplyView.m
//  Azkar
//
//  Created by 王易 on 2018/8/27.
//  Copyright © 2018年 CPX. All rights reserved.
//

#import "ReplyView.h"
#import "CommentsView.h"
#import "ReplyCell.h"

/**
 回复View
 */
@interface ReplyView()<UITableViewDelegate, UITableViewDataSource, RefreshDelegate>

@property (nonatomic,weak) RefreshTableView *tableView;

@property (nonatomic,weak) UILabel *total;

@property (nonatomic,weak) UIImageView *iconV;

@property (nonatomic,weak) UILabel *userName;

@property (nonatomic,weak) UILabel *desc;

@property (nonatomic,weak) UILabel *message;

@property (nonatomic,weak) MyRelativeLayout *moreLayout;

@property (nonatomic,weak)  UIButton *likeButton;

@property (nonatomic,weak) UILabel *likeCount;

@property (nonatomic,copy) NSDictionary *textStyle;

@property (nonatomic, strong) NSMutableArray *dataModel;

@property (nonatomic, assign) NSInteger pageIndex;

@property (nonatomic, strong) CommentsView *commentsView;

@end
@implementation ReplyView
- (NSMutableArray *)dataModel
{
    if (!_dataModel) {
        _dataModel = [NSMutableArray array];
    }
    return _dataModel;
}
- (NSDictionary *)textStyle
{
    if (!_textStyle) {
        _textStyle = @{@"defult":Color(@"#929292"),
                       @"selected":Color(@"#FF7878")};
    }
    return _textStyle;
}
- (instancetype)init
{
    if (self == [super init]) {
        
        [self initUI];
        
    }
    return self;

}
- (void)initUI
{
    self.backgroundColor = [UIColor clearColor];
    
    self.frame = [UIScreen mainScreen].bounds;
    
   __block MyRelativeLayout *rootLayout = [MyRelativeLayout new];
    rootLayout.myBottom = 0;
    rootLayout.myTop = 0;
    rootLayout.myHorzMargin= 0;
    rootLayout.backgroundColor = [UIColor clearColor];
    [self addSubview:rootLayout];
    
    UIView *bgView = [UIView new];
    bgView.myHorzMargin = 0;
    bgView.myBottom = 0;
    bgView.myHeight = [PhoneUtil tabbarAdjustHeight];
    bgView.backgroundColor = [UIColor whiteColor];
    [rootLayout addSubview:bgView];
    
    MyRelativeLayout *contentLayout = [MyRelativeLayout new];
    contentLayout.myTop = [PhoneUtil topAdjustHeightWithNavi:YES];
    contentLayout.myHorzMargin = 0;
    contentLayout.myBottom = [PhoneUtil tabbarAdjustHeight];;
    contentLayout.backgroundColor = [UIColor whiteColor];
    [rootLayout addSubview:contentLayout];
    
    CommentsView *commentsView = [CommentsView new];
    commentsView.lang_type = self.lang_type;
    [commentsView initContentUI];
    commentsView.sendBLock = ^(UITextField *input){
        NSString *Id = self.Id;
        NSString *url;
        if (!self.isPublic) {
   
            url = [NSString stringWithFormat:@"%@/%@/comments",BlessBlog,Id];
        }else{
           
            url = [NSString stringWithFormat:@"%@/%@/comments",PublicBless,Id];
        }
        if (!Id || !self.commentsModel.recomm_id) {
            [AlertTools showMessage:TLString(@"error")];
            return;
        }

        [AlertTools showLoading];
        [[AzkarApi postData:url withParm:@{@"content":input.text,@"comment_type":@"2",@"recomm_id":self.commentsModel.ID}]subscribeNext:^(id x) {
            [AlertTools hideLoading];
            input.text = nil;
            self.tableView.isRefreshing = YES;
            
            self.commentsModel.cnt_recommends = [NSString stringWithFormat:@"%ld",self.dataModel.count + 1];
            self.commentsModel = self.commentsModel;
            [[NSNotificationCenter defaultCenter]postNotificationName:ReplyComments_Const object:nil];
        } error:^(NSError *error) {
//            [AlertTools hideLoading];
            if ([error.userInfo[@"code"] integerValue] == -2) {
                [[SKPopupHelper shareInstance] pop_hide];
            }
        }];
    };
    [contentLayout addSubview:commentsView];
    self.commentsView = commentsView;
    
    MyBaseLayout *replysLayout = [self addReplysView:contentLayout];
    
    
    RefreshTableView *tableView = [[RefreshTableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.myHorzMargin = 0;
    tableView.backgroundColor = Color(@"#F7F7F7");
    tableView.topPos.equalTo(replysLayout.bottomPos);
    tableView.bottomPos.equalTo(commentsView.topPos);
    tableView.estimatedRowHeight = 44;
    
    tableView.estimatedSectionFooterHeight = 0;
    
    tableView.estimatedSectionHeaderHeight = 0;
    
    tableView.backgroundColor = Color(@"#F7F7F7");
    
    self.tableView = tableView;
    
    [contentLayout addSubview:tableView];
    
    self.tableView.dataSource = self;
    
    self.tableView.delegate = self;
    
    self.tableView.tableFooterView = [UIView new];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.refreshDelegate = self;
    
    self.tableView.canHeaderRefresh = YES;
    
    self.tableView.canFooterRefresh = YES;
    
    self.tableView.isRefreshing = YES;
    
    [ReplyCell registerClassToTable:self.tableView];
   
}

- (void)setLang_type:(NSString *)lang_type{
    _lang_type = lang_type;
    self.commentsView.lang_type = lang_type;
}

- (void)loadData
{
    
    NSString *Id ;
    NSString *url;
    if (!self.isPublic) {
        Id = self.commentsModel.ID;
        url = [NSString stringWithFormat:@"%@/%@/comment",BlessComment,Id];
    }else{
        Id = self.commentsModel.ID;
        url = [NSString stringWithFormat:@"%@/%@/comment",PublicBlessComment,Id];
    }
    if (!Id) {
        self.tableView.isRefreshing = NO;
        return;
    }
    
    [[AzkarApi getData:url withParm:@{@"limit":@"10",@"offset":[NSString stringWithFormat:@"%ld",self.pageIndex * 10 ]}] subscribeNext:^(id x) {
        self.tableView.isRefreshing = NO;
        self.tableView.isLoadingMoreData = NO;
        NSDictionary *data;
        if (x) {
            
            data = @{@"data":x};
        ReplyCommentModel *model = [ReplyCommentModel yy_modelWithDictionary:data];
        
        [self.dataModel addObjectsFromArray:model.data];
        
        if (model.data.count < 10) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            self.pageIndex ++ ;
        }
        }
     
        [self.tableView reloadData];
    } error:^(NSError *error) {
        if (error && error.userInfo[@"code"] && [error.userInfo[@"code"] integerValue] == -2) {
            [[SKPopupHelper shareInstance] pop_hide];
        }
        self.tableView.isRefreshing = NO;
        self.tableView.isLoadingMoreData = NO;
    }];
}

- (void)onRefreshing:(id)control {
    
    self.pageIndex = 0;
    
    [self.tableView.mj_footer resetNoMoreData];
    
    [self.dataModel removeAllObjects];
    
    [self loadData];
}
- (void)onLoadingMoreData:(id)control {
    [self loadData];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataModel.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ReplyCell *cell = [tableView dequeueReusableCellWithIdentifier:[ReplyCell reuseIdentifier]];
    cell.commentsModel = self.dataModel[indexPath.row];
    WeakSelf
    cell.likeBlock = ^(ReplyListModel *commentsModel) {
        StrongSelf
        
        if (!commentsModel.ID ) {
            return;
        }
        [AlertTools showLoading];
        
        NSString *url;
        if (!self.isPublic) {
            url = [NSString stringWithFormat:@"%@/%@/comment",BlessComment,commentsModel.ID];
        }else{
            url = [NSString stringWithFormat:@"%@/%@/comment",PublicBlessComment,commentsModel.ID];
        }
        
        if(!commentsModel.like){
            WeakSelf
            [[AzkarApi postData:url withParm:nil]subscribeNext:^(id x) {
                StrongSelf
                [AlertTools hideLoading];
                commentsModel.like = YES;
                commentsModel.cnt_like = [NSString stringWithFormat:@"%@",x];
                [self.tableView reloadRowAtIndexPath:indexPath withRowAnimation:0];

        
            } error:^(NSError *error) {
//                [AlertTools hideLoading];
                if ([error.userInfo[@"code"] integerValue] == -2) {
                    [[SKPopupHelper shareInstance] pop_hide];
                }
            }];
        }else{
            WeakSelf
            [[AzkarApi deleteData:url withParm:nil]subscribeNext:^(id x) {
                StrongSelf
                [AlertTools hideLoading];
                commentsModel.like = NO;
                commentsModel.cnt_like = [NSString stringWithFormat:@"%@",x];
                
                [self.tableView reloadRowAtIndexPath:indexPath withRowAnimation:0];

        
            } error:^(NSError *error) {
//                [AlertTools hideLoading];
            }];
            
        }
    };
    return cell;
}
- (void)setCommentsModel:(CommentsModel *)commentsModel
{
    _commentsModel = commentsModel;
      [self configUIWithModel];
}
- (MyBaseLayout *)addReplysView:(MyBaseLayout *)superLayout
{
    MyRelativeLayout *replysLayout = [MyRelativeLayout new];
    replysLayout.backgroundColor = [UIColor whiteColor];
    replysLayout.padding = UIEdgeInsetsMake(12, 12, 24, 12);
    replysLayout.myHorzMargin = 0;
    replysLayout.wrapContentHeight = YES;
    [superLayout addSubview:replysLayout];
    
    UILabel *total = [UILabel new];
    self.total = total;
    total.font = FontSize(20);
    total.textColor = Color(@"#002812");
    total.myLeading = total.myTop = 0;
    total.wrapContentSize = YES;
    [replysLayout addSubview:total];

    
    UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteButton.myTrailing = 0;
    deleteButton.myTop = 0;
    [deleteButton changeImage:Image(@"close_btn_black")];
    deleteButton.myWidth = deleteButton.myHeight = 30;
    [replysLayout addSubview:deleteButton];
    [deleteButton setHyb_onTouchUp:^(UIButton *sender) {
         [[SKPopupHelper shareInstance] pop_hide];
    }];
    
    [self addMoreMessage:replysLayout];
    

    return replysLayout;
}
- (void)addlikeLayout:(MyBaseLayout *)baseLayout
{
    MyRelativeLayout *likeLayout =[MyRelativeLayout  new];
    likeLayout.myLeading = 42;
    likeLayout.topPos.equalTo(self.message.bottomPos).offset(20);
    likeLayout.myTrailing = 0;
    likeLayout.wrapContentHeight = YES;
    [baseLayout addSubview:likeLayout];
    
    UIButton *likeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.likeButton = likeButton;
    likeButton.myWidth = likeButton.myHeight = 30;
    [likeButton changeImage:Image(@"like_ic")];
    likeButton.myTrailing = 0;
    likeButton.myTop = 0;
    [likeLayout addSubview:likeButton];
    WeakSelf
    [likeButton setHyb_onTouchUp:^(UIButton *sender) {
       
        
        StrongSelf
        
        if (!self.commentsModel.ID) {
            return;
        }
        [AlertTools showLoading];
        
        NSString *url;
        if (!self.isPublic) {
            url = [NSString stringWithFormat:@"%@/%@/comment",BlessComment,self.commentsModel.ID];
        }else{
            url = [NSString stringWithFormat:@"%@/%@/comment",PublicBlessComment,self.commentsModel.ID];
        }
        
        if(!self.commentsModel.like){
            WeakSelf
            [[AzkarApi postData:url withParm:nil]subscribeNext:^(id x) {
                StrongSelf
                [AlertTools hideLoading];
                self.commentsModel.like = YES;
                self.commentsModel.cnt_like = [NSString stringWithFormat:@"%@",x];
                [[NSNotificationCenter defaultCenter]postNotificationName:ReplyComments_Const object:nil];
                self.commentsModel = self.commentsModel;
            } error:^(NSError *error) {
//                [AlertTools hideLoading];
            }];
        }else{
            WeakSelf
            [[AzkarApi deleteData:url withParm:nil]subscribeNext:^(id x) {
                StrongSelf
                [AlertTools hideLoading];
                self.commentsModel.like = NO;
                self.commentsModel.cnt_like = [NSString stringWithFormat:@"%@",x];
                [[NSNotificationCenter defaultCenter]postNotificationName:ReplyComments_Const object:nil];
                self.commentsModel = self.commentsModel;
            } error:^(NSError *error) {
//                [AlertTools hideLoading];
            }];
            
        }
        
    }];
    
    UILabel *likeCount = [UILabel new];
    self.likeCount  =likeCount;
    likeCount.myLeading = likeCount.myCenterY = 0;
    likeCount.wrapContentSize = YES;
    likeCount.font = FontSize(14);
    likeCount.textColor = Color(@"#929292");
    [likeLayout addSubview:likeCount];
    
    
}
- (void)addMoreMessage:(MyBaseLayout *)baseLayout
{
    MyRelativeLayout *relativeLayout = [MyRelativeLayout new];
    self.moreLayout = relativeLayout;
    relativeLayout.topPos.equalTo(self.total.bottomPos).offset(10);
    relativeLayout.myHorzMargin = 0;
    relativeLayout.wrapContentHeight = YES;
    [baseLayout addSubview:relativeLayout];
    
    UIImageView *iconV = [UIImageView new];
    self.iconV = iconV;
    iconV.layer.cornerRadius = 17;
    iconV.layer.masksToBounds = YES;
    iconV.myLeading = iconV.myTop = 0;
    iconV.myWidth = iconV.myHeight = 34;
    [relativeLayout addSubview:iconV];
    
    UILabel *userName = [UILabel new];
    self.userName = userName;
    userName.wrapContentHeight = YES;
    userName.numberOfLines = 1;
    userName.leadingPos.equalTo(iconV.trailingPos).offset(8);
    userName.myTrailing = 0;
    userName.textColor = Color(@"#525252");
    userName.font = FontSize(13);
    userName.myTop = 0;
    [relativeLayout addSubview:userName];
    
    UILabel *desc = [UILabel new];
    self.desc = desc;
    desc.leadingPos.equalTo(userName.leadingPos);
    desc.myTrailing = 0;
    desc.topPos.equalTo(userName.bottomPos).offset(3);
    desc.font = FontSize(11);
    desc.textColor = Color(@"#929292");
    desc.wrapContentHeight = YES;
    [relativeLayout addSubview:desc];
    
    UILabel *message = [UILabel new];
    self.message = message;
    message.topPos.equalTo(relativeLayout.bottomPos).offset(10);
    message.myLeading = 42;
    message.myTrailing = 0;
    message.wrapContentHeight = YES;
    message.textColor = Color(@"#525252");
    message.font = FontSize(15);
    [baseLayout addSubview:message];
    
    [self addlikeLayout:baseLayout];
}
- (void)configUIWithModel
{
    self.total.text = [NSString stringWithFormat:@"%@ %@",self.commentsModel.cnt_recommends,TLString(@"Replys")];
    [self.total sizeToFit];
    
    [self.iconV sd_setImageWithURL:[NSURL URLWithString:self.commentsModel.avatar] placeholderImage:ICONIMGE];
    
    self.userName.text = self.commentsModel.commenter_name;
    [self.userName sizeToFit];
    
    NSString *time = [DateHelper dateStrFromTimeStamp:self.commentsModel.comment_time dateFormat:@"dd/MM HH:mm"];
    self.desc.text = time;
    [self.desc sizeToFit];
    
    self.message.text = self.commentsModel.content;
    [self.message sizeToFit];
    
    [self.likeButton changeImage:self.commentsModel.like ? Image(@"like_ic_s") :Image(@"like_ic")];
    
    NSString *likeAttr = [NSString stringWithFormat:@"<selected>%ld</selected>  <defult>%@</defult>",[self.commentsModel.cnt_like integerValue],TLString(@"people likes")];
    self.likeCount.attributedText = [likeAttr attributedStringWithStyleBook:self.textStyle];
    
    [self.likeCount sizeToFit];
    
}
- (void)showView
{
     [[SKPopupHelper shareInstance] skpop_FlyInFromBottom:self defaultHideEnable:YES alphaBG:0.3];
}
@end
